<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="896" @ok="handleSubmit">
      <BasicForm @register="registerForm" ref="formRef" name="TestCpMainForm" />
      <!-- 子表单区域 -->
      <a-tabs v-model:activeKey="activeKey" animated @change="handleChangeTabs">
        <a-tab-pane tab="接口授权" key="testCpInterface" :forceRender="true">
          <JVxeTable
            keep-source
            resizable
            ref="testCpInterface"
            :loading="testCpInterfaceTable.loading"
            :columns="testCpInterfaceTable.columns"
            :dataSource="testCpInterfaceTable.dataSource"
            :height="340"
            :disabled="formDisabled"
            :rowNumber="true"
            :rowSelection="true"
            :toolbar="true"
            />
        </a-tab-pane>
        <a-tab-pane tab="报警信息" key="testCpError" :forceRender="true">
          <JVxeTable
            keep-source
            resizable
            ref="testCpError"
            :loading="testCpErrorTable.loading"
            :columns="testCpErrorTable.columns"
            :dataSource="testCpErrorTable.dataSource"
            :height="340"
            :disabled="formDisabled"
            :rowNumber="true"
            :rowSelection="true"
            :toolbar="true"
            />
        </a-tab-pane>
      </a-tabs>

  </BasicModal>
</template>

<script lang="ts" setup>
    import {ref, computed, unref,reactive} from 'vue';
    import {BasicModal, useModalInner} from '/@/components/Modal';
    import {BasicForm, useForm} from '/@/components/Form/index';
    import { JVxeTable } from '/@/components/jeecg/JVxeTable'
    import { useJvxeMethod } from '/@/hooks/system/useJvxeMethods.ts'
    import {formSchema,testCpInterfaceJVxeColumns,testCpErrorJVxeColumns} from '../TestCpMain.data';
    import {saveOrUpdate,queryTestCpInterface,queryTestCpError} from '../TestCpMain.api';
    import { VALIDATE_FAILED } from '/@/utils/common/vxeUtils'
    import { useMessage } from '/@/hooks/web/useMessage';
    import { getDateByPicker } from '/@/utils';
    //日期个性化选择
    const fieldPickers = reactive({
    });
      const testCpInterfaceFieldPickers = reactive({
      });
      const testCpErrorFieldPickers = reactive({
      });
    const { createMessage } = useMessage();
    // Emits声明
    const emit = defineEmits(['register','success']);
    const isUpdate = ref(true);
    const formDisabled = ref(false);
    const refKeys = ref(['testCpInterface', 'testCpError', ]);
    const activeKey = ref('testCpInterface');
    const testCpInterface = ref();
    const testCpError = ref();
    const tableRefs = {testCpInterface, testCpError, };
    const testCpInterfaceTable = reactive({
          loading: false,
          dataSource: [],
          columns:testCpInterfaceJVxeColumns
    })
    const testCpErrorTable = reactive({
          loading: false,
          dataSource: [],
          columns:testCpErrorJVxeColumns
    })
    //表单配置
    const [registerForm, {setProps,resetFields, setFieldsValue, validate}] = useForm({
        schemas: formSchema,
        showActionButtonGroup: false,
        baseColProps: {span: 12}
    });
     //表单赋值
    const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
        //重置表单
        await reset();
        setModalProps({confirmLoading: false,showCancelBtn:data?.showFooter,showOkBtn:data?.showFooter});
        isUpdate.value = !!data?.isUpdate;
        formDisabled.value = !data?.showFooter;
        if (unref(isUpdate)) {
            //表单赋值
            await setFieldsValue({
                ...data.record,
            });
             requestSubTableData(queryTestCpInterface, {id:data?.record?.id}, testCpInterfaceTable)
             requestSubTableData(queryTestCpError, {id:data?.record?.id}, testCpErrorTable)
        }
        // 隐藏底部时禁用整个表单
       setProps({ disabled: !data?.showFooter })
    });
    //方法配置
    const [handleChangeTabs,handleSubmit,requestSubTableData,formRef] = useJvxeMethod(requestAddOrEdit,classifyIntoFormData,tableRefs,activeKey,refKeys);

    //设置标题
    const title = computed(() => (!unref(isUpdate) ? '新增' : !unref(formDisabled) ? '编辑' : '详情'));

    async function reset(){
      await resetFields();
      activeKey.value = 'testCpInterface';
      testCpInterfaceTable.dataSource = [];
      testCpErrorTable.dataSource = [];
    }
    function classifyIntoFormData(allValues) {
         let main = Object.assign({}, allValues.formValue)
         return {
           ...main, // 展开
           testCpInterfaceList: allValues.tablesValue[0].tableData,
           testCpErrorList: allValues.tablesValue[1].tableData,
         }
       }
    //表单提交事件
    async function requestAddOrEdit(values) {
        try {
            // 预处理日期数据
            changeDateValue(values);
            setModalProps({confirmLoading: true});
            //提交表单
            await saveOrUpdate(values, isUpdate.value);
            //关闭弹窗
            closeModal();
            //刷新列表
            emit('success');
        } finally {
            setModalProps({confirmLoading: false});
        }
    }

    /**
     * 处理日期值
     * @param formData 表单数据
     */
    const changeDateValue = (formData) => {
      if (formData && fieldPickers) {
          for (let key in fieldPickers) {
              if (formData[key]) {
                  formData[key] = getDateByPicker(formData[key], fieldPickers[key]);
              }
          }
      }
      if(formData && formData.testCpInterfaceList && formData.testCpInterfaceList.length > 0){
          formData.testCpInterfaceList.forEach(subFormData=>{
              for (let key in testCpInterfaceFieldPickers) {
                  if (subFormData[key]) {
                      subFormData[key] = getDateByPicker(subFormData[key], testCpInterfaceFieldPickers[key]);
                  }
              }
          })
      }
      if(formData && formData.testCpErrorList && formData.testCpErrorList.length > 0){
          formData.testCpErrorList.forEach(subFormData=>{
              for (let key in testCpErrorFieldPickers) {
                  if (subFormData[key]) {
                      subFormData[key] = getDateByPicker(subFormData[key], testCpErrorFieldPickers[key]);
                  }
              }
          })
      }
    };
</script>

<style lang="less" scoped>
	/** 时间和数字输入框样式 */
  :deep(.ant-input-number) {
    width: 100%;
  }

  :deep(.ant-calendar-picker) {
    width: 100%;
  }
</style>